<?php
namespace App\Controller\App;

use App\Query\ConfigQuery;
use App\Query\UserQuery;
use App\Query\UserLogQuery;

class UserController extends Controller
{
    // 信息
    public function info()
    {
        return UserQuery::load($this->auth()->model());
    }
    
    // 下级用户列表
    public function list()
    {
        return UserQuery::user($this->auth()->model())->paginate(15)->toArray();
    }
    
    // 日志
    public function log()
    {
        return UserLogQuery::query(
            UserLogQuery::user($this->auth()),
            $this->inputs('type', 'money_type')
        )->paginate(15)->toArray();
    }
    
    // 资产互转
    public function to()
    {
        $user = $this->auth();
        
        $config = ConfigQuery::get();
        
        // 互转类型
        $type = $this->input('type');
        // 接收
        $to = $this->input('to');
        // 金额
        $money = (int) $this->input('money');
        
        // 判断类型正确
        if($type == $to)
        {
            $this->error('error');
        }
        
        // 组合字段
        $name = $type . '_to_' . $to;
        
        // 判断配置中是否存在
        if(! ($config[$name] ?? 0))
        {
            $this->error('money_type_to');
        }
        
        // 倍数
        if(!$money || $money % $config['money_to'])
        {
            $this->error('double');
        }
        
        // 减资产
        if($user->makeMoney($type, $money, '资产互换'))
        {
            // 加资产
            $user->addMoney($to, $money, '资产互换');
            
            // 扣税
            $user->makeMoney($to, ConfigQuery::bi($config, $name . '_tax', $money), '资产互换税收', 'tax');
            
            $this->message('ok');
        }

        $this->error($type);
    }
    
    // 转入钱包
    public function wallet()
    {
        $user = $this->auth();
        
        // 金额
        $money = (int) $this->input('money');

        // 扣余额
        if($user->makeMoney('money', $money, '转入钱包'))
        {
            // 转入钱包
            $user->addMoney('money_wallet', $money, '转入钱包');
            
            // 变动时间
            $user->setMoneyWalletTime();
            
            $this->message('ok');
        }
        
        $this->error('money');
    }
    
    // 转出钱包
    public function walletOut()
    {
        $user = $this->auth();
        
        // 金额
        $money = (int) $this->input('money');

        // 扣钱包
        if($user->makeMoney('money_wallet', $money, '转出钱包'))
        {
            // 加余额
            $user->addMoney('money', $money, '转出钱包');
            
            $this->message('ok');
        }
        
        $this->error('money_wallet');
    }
}
